/**
 * 文件下载
 * @param {Any} data  name:文件名
 * @param {Any} data  url:若为地址则直接下载，若为文件流则需定文件类型
 * @param {Any} data  type:类型 excel|json 类型为空时则直接下载,不为空时url为Blob数据
 * @param {Any} data  headers:请求头
 */
export function fileDownload({ data }: { data: any }) {
  if (!data) return console.error({ message: '参数有误', function: this })

  if (!Array.isArray(data)) data = [data]

  data.map((item: any) => {
    let { type, name, url, headers, param } = item

    if (type == 'blob') {
      const request = new XMLHttpRequest()
      request.responseType = 'blob'
      request.open('get', url, true)
      Object.keys(headers).forEach((key) => {
        request.setRequestHeader(key, headers[key])
      })
      request.onreadystatechange = () => {
        if (
          request.readyState == XMLHttpRequest.DONE &&
          request.status == 200
        ) {
          const a = document.createElement('a')
          a.href = URL.createObjectURL(request.response)
          a.download = name || ''
          a.style.display = 'none'
          a.click()
          document.body.removeChild(a)
        }
      }
      if (param) {
        request.send(JSON.stringify(param))
        return
      }

      request.send(null)
      return
    }

    const a = document.createElement('a')
    a.download = name || ''
    a.style.display = 'none'
    a.href = url

    switch (type) {
      case 'excel':
        type =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
        a.href = window.URL.createObjectURL(new Blob([url], { type }))
        break
      case 'json':
        type = 'text/json'
        a.href = window.URL.createObjectURL(new Blob([url], { type }))
        break
    }

    a.click()
    document.body.removeChild(a)
  })
}
